package com.vipheyue.lanjingapp.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.hardware.SensorEvent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.util.LogUtils;
import com.umeng.scrshot.UMScrShotController;
import com.umeng.scrshot.adapter.UMAppAdapter;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sensor.UMSensor;
import com.umeng.socialize.sensor.beans.ShakeMsgType;
import com.umeng.socialize.sensor.controller.UMShakeService;
import com.umeng.socialize.sensor.controller.impl.UMShakeServiceFactory;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.SmsHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;
import com.vipheyue.lanjingapp.R;
import com.vipheyue.lanjingapp.bean.FavoritesTable;
import com.vipheyue.lanjingapp.bean.Job;
import com.vipheyue.lanjingapp.map.RouteActivity;
import com.vipheyue.lanjingapp.utils.GsonUtils;
import com.vipheyue.lanjingapp.utils.ImageUtil;
import com.vipheyue.lanjingapp.utils.MyDb;
import com.vipheyue.lanjingapp.view.RoundedLetterView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class JobDetailActivity extends AppCompatActivity implements OnItemClickListener {


    @Bind(R.id.rl_menu_left)
    RelativeLayout rl_menu_left;
    @Bind(R.id.tv_Menu_Title)
    TextView tv_Menu_Title;
    @Bind(R.id.iv_menu_right)
    ImageView iv_menu_right;
    @Bind(R.id.rl_menu_right)
    RelativeLayout rl_menu_right;
    @Bind(R.id.rlv_jobType)
    RoundedLetterView rlv_jobType;
    @Bind(R.id.tv_jobTitile)
    TextView tv_jobTitile;
    @Bind(R.id.tv_workAreaType)
    TextView tv_workAreaType;
    @Bind(R.id.tv_createTime)
    TextView tv_createTime;
    @Bind(R.id.tv_maxSalaryAndType)
    TextView tv_maxSalaryAndType;
    @Bind(R.id.tv_jobRebate)
    TextView tv_jobRebate;
    @Bind(R.id.tv_jobWelfare)
    TextView tv_jobWelfare;
    @Bind(R.id.tv_contactsPeople)
    TextView tv_contactsPeople;
    @Bind(R.id.tv_contactsPhone)
    TextView tv_contactsPhone;
    @Bind(R.id.tv_workAddressDetail)
    TextView tv_workAddressDetail;
    @Bind(R.id.tv_publisherCompany)
    TextView tv_publisherCompany;
    @Bind(R.id.tv_description)
    TextView tv_description;
    @Bind(R.id.tv_collect)
    TextView tv_collect;
    @Bind(R.id.tv_call)
    TextView tv_call;
    @Bind(R.id.ref_point_company)
    TextView ref_point_company;
    @Bind(R.id.rl_company_see)
    RelativeLayout rl_company_see;
    @Bind(R.id.tv_company)
    TextView tv_company;
    @Bind(R.id.tv_comany_description)
    TextView tv_comany_description;
    @Bind(R.id.iv_company_logo)
    ImageView iv_company_logo;
    @Bind(R.id.tv_word_point)
    TextView tv_word_point;
    @Bind(R.id.rl_work_point)
    RelativeLayout rl_work_point;
    private Job job;
    private String jobStr;
/**************分享****************/
UMSocialService mController;
    private UMImage mShareImageview;
    private String   shareTitle = "";
    private String shareContent="";
    //设置点击分享内容的跳转链接
    private String  targetUrl = "http://www.bbbbbb.com";
    private Dialog dialog;

    /******************************/
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_job_detail);
        ButterKnife.bind(this);
//        StatusBarCompat.compat(this, 0xFF00ABEC);
        initData();
    }

    private void initData() {
        Intent intent = this.getIntent();
        jobStr = intent.getStringExtra("jobStr");
        LogUtils.i("jobStr" + jobStr);
        job = GsonUtils.fromJson(jobStr, Job.class);

        tv_jobTitile.setText(job.getJobTitle());
        rlv_jobType.setTitleText(job.getJobType());
        tv_workAreaType.setText(job.getWorkAreaType());
        tv_createTime.setText(job.getUpdatedAt());
        tv_maxSalaryAndType.setText(job.getMaxSalary() + "/" + job.getSalaryType());

        tv_workAddressDetail.setText(job.getWorkAddressDetail());
//        tv_publisherCompany.setText(job.getPublisherCompany().getCompanyName());
        tv_contactsPeople.setText(job.getContactsPeople());
        tv_contactsPhone.setText(job.getContactsPhone());
        tv_description.setText(job.getDetailDescription());
//        tv_description.setText("松松送送送送送送送送送送送送送送送送送送送送送送送送送送送送松松送送送送送送送送送送送送送送送送送送送送送送送送送送送送松松送送送送送送送送送送送送送送送送送送送送送送送送送送送送松松送送送送送送送送送送送送送送送送送送送送送送送送送送送送松松送送送送送送送送送送送送送送送送送送送送送送送送送送送送松松送送送送送送送送送送送送送送送送送送送送送送送送送送送送松松送送送送送送送送送送送送送送送送送送送送送送送送送送送送松松送送送送送送送送送送送送送送送送送送送送送送送送送送送送");
        tv_Menu_Title.setText("工作详情");
        iv_menu_right.setVisibility(View.VISIBLE);
        tv_jobRebate.setText(job.getJobRebate());
        ArrayList<String> list=job.getJobWelfareList();
        StringBuffer sb = new StringBuffer();
        for (String str : list) {
            sb.append(str + "  ");
        }
        tv_jobWelfare.setText(sb.toString());
        tv_company.setText(job.getCompanyName());
        tv_comany_description.setText(job.getCompanyDescription());
        if (job.getCompanyLogo() != null && !TextUtils.isEmpty(job.getCompanyLogo().getUrl())) {
            ImageUtil.setImageURI(this, iv_company_logo, job.getCompanyLogo().getUrl());
            LogUtils.i("------>" + job.getCompanyLogo().getFileUrl(this));
        }


        if (haveCollect()) {
            Drawable drawable = getResources().getDrawable(R.drawable.ic_action_star_true);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tv_collect.setCompoundDrawables(drawable, null, null, null);
        }
    }

    private Boolean haveCollect() {
        Boolean havedCollect = false;
        List<FavoritesTable> FavoritesTables = MyDb.getObjectTable(this);
        if (FavoritesTables == null || FavoritesTables.size() == 0) {
            return havedCollect;
        }
        for (FavoritesTable favoritesTable1 : FavoritesTables) {
            if (favoritesTable1.getJobId().equals(job.getObjectId())) {
                havedCollect = true;

            }
        }
        return havedCollect;
    }


    @OnClick({R.id.rl_menu_left, R.id.rl_company_see, R.id.tv_collect, R.id.tv_call,R.id.iv_menu_right,R.id.rl_work_point})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_menu_left:
                finish();
                break;
            case R.id.rl_company_see:
                Intent companyIntent = new Intent(this, CompanyDetailActivity.class);
                companyIntent.putExtra("jobStr", jobStr);
                startActivity(companyIntent);
                break;
            case R.id.tv_collect:
                FavoritesTable favoritesTable = new FavoritesTable();
                favoritesTable.setJobId(job.getObjectId());


                if (haveCollect()) {
                    Drawable drawable = getResources().getDrawable(R.drawable.ic_action_star_0);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    tv_collect.setCompoundDrawables(drawable, null, null, null);
                    DbUtils db = DbUtils.create(this);
                    try {
                        db.deleteById(FavoritesTable.class, job.getObjectId());
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                } else {
                    Drawable drawable = getResources().getDrawable(R.drawable.ic_action_star_true);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    tv_collect.setCompoundDrawables(drawable, null, null, null);
                    MyDb.saveOrUpdate(this, favoritesTable);
                }


                List<FavoritesTable> FavoritesTables = MyDb.getObjectTable(this);
                for (FavoritesTable favoritesTable1 : FavoritesTables) {
                    LogUtils.i("后------>  " + favoritesTable1.getJobId());
                }
                break;
            case R.id.tv_call:
                //创建意图
                Intent intent = new Intent();
                intent.setAction("android.intent.action.CALL");
                intent.addCategory("android.intent.category.DEFAULT");//内部自动添加类别
                intent.setData(Uri.parse("tel:" + job.getContactsPhone()));
                //开始行为
                startActivity(intent);
                break;
            case R.id.iv_menu_right:
//                registerShakeToShare();
//                registerShakeToShortCut();
//                Toast.makeText(this, "摇一摇分享", Toast.LENGTH_SHORT).show();
                shareTitle = job.getJobTitle();
                shareContent=job.getJobRebate()+"    联系电话:"+job.getContactsPhone()+"\r\n工作细节:"+job.getDetailDescription();
                preShare();
                detailShare();
                break;
            case R.id.rl_work_point:
                new AlertView("选择地图", null, "取消", null,
                        new String[]{"百度地图", "高德地图"},
                        this, AlertView.Style.ActionSheet, this).show();
                break;
        }
    }
    private void registerShakeToShare() {
        // 声明mShakeController, 参数1为sdk 控制器描述符
        UMShakeService mShakeController = UMShakeServiceFactory
                .getShakeService("com.umeng.share");
        /**
         * 摇一摇截图,直接分享 参数1: 当前所属的Activity 参数2: 截图适配器 参数3: 要用户可选的平台,最多支持五个平台 参数4:
         * 传感器监听器，包括摇一摇完成后的回调函数onActionComplete, 可在此执行类似于暂停游戏、视频等操作;
         * 还有分享完成、取消的回调函数onOauthComplete、onShareCancel。
         */
        preShare();
        detailShare();
        UMAppAdapter appAdapter = new UMAppAdapter(this);
        // 配置平台
        List<SHARE_MEDIA> platforms = new ArrayList<SHARE_MEDIA>();
        platforms.add( SHARE_MEDIA.QQ );
        platforms.add( SHARE_MEDIA.QZONE );
        platforms.add( SHARE_MEDIA.WEIXIN );
        platforms.add( SHARE_MEDIA.WEIXIN_CIRCLE );
        new SmsHandler().addToSocialSDK();
        // 通过摇一摇控制器来设置文本分享内容
        mShakeController.setShareContent(shareTitle);
        mShakeController.setShakeMsgType(ShakeMsgType.PLATFORM_SCRSHOT);

        mShakeController.registerShakeListender(this, appAdapter,
                2000, false, platforms, mSensorListener);
        mShakeController.enableShakeSound(false);

    }

    public UMSensor.OnSensorListener mSensorListener = new UMSensor.OnSensorListener() {
        @Override
        public void onStart() {
        }
        /**
         * 分享完成后回调
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int eCode, SocializeEntity entity) {
            Toast.makeText(JobDetailActivity.this, "分享完成", Toast.LENGTH_SHORT).show();
        }

        /**
         * @Description: 摇一摇动作完成后回调
         */
        @Override
        public void onActionComplete(SensorEvent event) {
//            Toast.makeText(ShareActivity.this, "用户摇一摇，可在这暂停游戏", Toast.LENGTH_SHORT).show();
        }

        /**
         * @param button 用户在分享窗口点击的按钮，有取消和分享两个按钮
         * @Description: 用户点击分享窗口的取消和分享按钮触发的回调
         */
        @Override
        public void onButtonClick(UMSensor.WhitchButton button) {
            if (button == UMSensor.WhitchButton.BUTTON_CANCEL) {
//                Toast.makeText(ShareActivity.this, "取消分享,游戏重新开始", Toast.LENGTH_SHORT).show();
            } else {
                // 分享中, ( 用户点击了分享按钮 )
            }
        }
    };

    private void registerShakeToShortCut() {
        UMShakeService mShakeController = UMShakeServiceFactory
                .getShakeService("umeng");
        // 摇一摇截图
        mShakeController.registerShakeToScrShot(this,
                new UMAppAdapter(this), 1500, true,
                mScreenshotListener);
    }
    @Override
    public void onItemClick(Object o, int position) {
        if (position == 0) {
                    try {
                    //移动APP调起Android百度地图方式举例
                    Intent    intent = Intent.getIntent("intent://map/geocoder?address="+job.getWorkAddressDetail()+"&src=yourCompanyName|yourAppName#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                    startActivity(intent); //启动调用
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(this, "请安装百度地图", Toast.LENGTH_SHORT).show();
                }
        }
        if (position == 1) {
            Intent intentGD = new Intent(this, RouteActivity.class);
            intentGD.putExtra("WorkAddressDetail", job.getWorkAddressDetail());
            startActivity(intentGD);
        }
    }
    /**
     * 截图监听器，返回屏幕截图
     */
    private UMScrShotController.OnScreenshotListener mScreenshotListener = new UMScrShotController.OnScreenshotListener() {

        @Override
        public void onComplete(Bitmap bmp) {
            if (bmp != null) {

                mShareImageview = new UMImage(JobDetailActivity.this, bmp);
             String path=   BitmapToFile(bmp);
//              uploadFile(path);
            }

        }
    };

    private String  BitmapToFile(Bitmap bitmap){
        FileOutputStream fout = null;
        File file = new File(getCacheDir(), "BitmapToFilt.jpg");
        String filename = file.getAbsolutePath();
        try {
            fout = new FileOutputStream(filename);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                fout.flush();
                fout.close();
                return  file.getAbsolutePath();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  file.getAbsolutePath();
    }
//    private void uploadFile(String filePath) {
//                dialog = CustomDialog.onCreateDialog(JobDetailActivity.this);
//                dialog.show();
//        BTPFileResponse response = BmobProFile.getInstance(this).upload(filePath, new UploadListener() {
//
//            @Override
//            public void onSuccess(String fileName,String url,BmobFile file) {
//                dialog.dismiss();
//                targetUrl=file.getUrl();
//                preShare();
//                detailShare();
//            }
//
//            @Override
//            public void onProgress(int progress) {
//                dialog.dismiss();
//            }
//
//            @Override
//            public void onError(int statuscode, String errormsg) {
//                dialog.dismiss();
//            }
//        });
//    }
    /**
     * 准备分享之前
     */
    private void preShare() {
        //TODO 替换id,和 密码
        /********分享功能*************************************/
        //参数1为当前Activity， 参数2为开发者在QQ互联申请的APP ID，参数3为开发者在QQ互联申请的APP kEY.
        UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this, "1104708077", "Ejd6EhaBcpNTHNwy");
        qqSsoHandler.addToSocialSDK();

        //参数1为当前Activity， 参数2为开发者在QQ互联申请的APP ID，参数3为开发者在QQ互联申请的APP kEY.
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, "1104708077", "Ejd6EhaBcpNTHNwy");
        qZoneSsoHandler.addToSocialSDK();

        // wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
        String appID = "wx45e40701506a0d92";//TODO 修改appid,和密码 第二个,第三个
        String appSecret = "ebbe2941ea7634f1f8cffc85f81df0a7";
// 添加微信平台
        UMWXHandler wxHandler = new UMWXHandler(this, appID, appSecret);
        wxHandler.addToSocialSDK();
// 支持微信朋友圈
        UMWXHandler wxCircleHandler = new UMWXHandler(this, appID, appSecret);
        wxCircleHandler.setToCircle(true);
        wxCircleHandler.addToSocialSDK();
        //新浪微博

    }

    private void detailShare() {
        // 首先在您的Activity中添加如下成员变量
        mController = UMServiceFactory.getUMSocialService("com.umeng.share");
        // 设置分享内容

        mController.setShareContent(shareTitle);
        // 设置分享图片, 参数2为图片的url地址
//        mController.setShareMedia(new UMImage(this, "http://www.umeng.com/images/pic/home/social/banner.png"));
        mController.setShareMedia(mShareImageview);
        mController.getConfig().removePlatform(SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN);
        /**QQ---------------------------------------------------*/
        QQShareContent qqShareContent = new QQShareContent();
        //设置分享文字
        qqShareContent.setShareContent(shareContent);
        //设置分享title
        qqShareContent.setTitle(shareTitle);
        //设置分享图片
        qqShareContent.setShareImage(mShareImageview);

        qqShareContent.setTargetUrl(targetUrl);
        mController.setShareMedia(qqShareContent);
        /**QQ--------END-------------------------------------------*/


        /**QZONE--------START-------------------------------------------*/

        QZoneShareContent qzone = new QZoneShareContent();
        //设置分享文字
        qzone.setShareContent(shareContent);
        //设置点击消息的跳转URL
        qzone.setTargetUrl(targetUrl);
        //设置分享内容的标题
        qzone.setTitle(shareTitle);
        //设置分享图片
        qzone.setShareImage(mShareImageview);
        mController.setShareMedia(qzone);
        /**QZONE--------END-------------------------------------------*/
        /**weixin--------start-------------------------------------------*/
        //设置微信好友分享内容
        WeiXinShareContent weixinContent = new WeiXinShareContent();
//设置分享文字
        weixinContent.setShareContent(shareContent);
//设置title
        weixinContent.setTitle(shareTitle);
//设置分享内容跳转URL
        weixinContent.setTargetUrl(targetUrl);
//设置分享图片
        weixinContent.setShareImage(mShareImageview);
        mController.setShareMedia(weixinContent);
        /**weixin--------END-------------------------------------------*/
        /**朋友圈--------start-------------------------------------------*/
//设置微信朋友圈分享内容
        CircleShareContent circleMedia = new CircleShareContent();
        circleMedia.setShareContent(shareContent);
//设置朋友圈title
        circleMedia.setTitle(shareTitle);
        circleMedia.setShareImage(mShareImageview);
        circleMedia.setTargetUrl(targetUrl);
        mController.setShareMedia(circleMedia);
        /**朋友圈--------END-------------------------------------------*/
        /**新浪--------start-------------------------------------------*/
        //设置新浪SSO handler
        mController.getConfig().setSsoHandler(new SinaSsoHandler());
        /**新浪--------END-------------------------------------------*/
        /**腾讯微博--------start-------------------------------------------*/
        //设置腾讯微博SSO handler
//        mController.getConfig().setSsoHandler(new TencentWBSsoHandler());
        /**腾讯微博--------END-------------------------------------------*/


        mController.getConfig().setSsoHandler(new SinaSsoHandler());

        // 是否只有已登录用户才能打开分享选择页
        mController.openShare(this, false);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Toast.makeText(this, "分享成功", Toast.LENGTH_SHORT).show();

        /**使用SSO授权必须添加如下代码 */
        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode);
        if (ssoHandler != null) {
            Toast.makeText(this, "分享成功", Toast.LENGTH_SHORT).show();
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }
}
